package controllers.initializer
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import com.utils.actionList.ActionListEvent;
	import com.utils.assetsFactory.AssetsFactory;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	public class Initializer extends EventDispatcher
	{
		protected var _loader:BulkLoader;
		
		public function Initializer()
		{
			super(null);
		}
		
		public function start():void
		{
			_loader = new BulkLoader("main");
			_loader.add( Ref.CONFIG_FILE );
			_loader.add( Ref.ASSETS_FILE );
			_loader.add( Ref.GUI_FILE );
			_loader.addEventListener(BulkProgressEvent.COMPLETE, onFilesLoadComplete, false,0, true);
			_loader.addEventListener(BulkLoader.ERROR, onFilesLoadError, false,0, true);
			_loader.start();
		}
		
		protected function onFilesLoadError (ev:Event):void
		{
			_loader.removeEventListener(BulkProgressEvent.COMPLETE, onFilesLoadComplete);
			_loader.removeEventListener(BulkLoader.ERROR, onFilesLoadError);
			
			// pendiente error ??	
		}

		protected function onFilesLoadComplete (ev:BulkProgressEvent):void
		{
			_loader.removeEventListener(BulkProgressEvent.COMPLETE, onFilesLoadComplete);
			_loader.removeEventListener(BulkLoader.ERROR, onFilesLoadError);
			
			Ref.model.configXML    = _loader.getXML( Ref.CONFIG_FILE );
			Ref.view.assetsFactory = _loader.getSprite( Ref.ASSETS_FILE ) as AssetsFactory;
			Ref.view.guiFactory    = _loader.getSprite( Ref.GUI_FILE ) as AssetsFactory;
			
			destroy();
			
			dispatchEvent( new ActionListEvent(ActionListEvent.EVT_ACTION_LIST_ITEM_COMPLETE));
		}
		
		public function destroy():void
		{
			if (_loader)
			{
				_loader.removeAll();
				BulkLoader.removeAllLoaders();
				_loader = null;
			}
		}
	}
}